package com.board.util;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.board.dto.PayInfoDto;
import com.board.entity.SeatEatOrder;
import com.board.entity.SendOrder;
import com.board.param.OrderPayParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class AlipayUtil {

    @Autowired
    private AlipayClient alipayClient;

    /**
     * 网页支付方法 参数:封装支付参数，需要包含订单号、支付金额、支付说明、详细描述（可选）、同步回调地址、异步回调地址
     */
    public String pagePay(OrderPayParam param) throws Exception {
        // 实例化网页支付请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置参数
        String content = "{\"timeout_express\":\""+param.getPayTimeOrder()+"m\",\"out_trade_no\":\"" + param.getOrderId() + "\"," + "\"total_amount\":\"" + param.getMoney()
                + "\"," + "\"subject\":\"" + param.getSubject() + "\"," + "\"body\":\"" + param.getBody() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";
        request.setBizContent(content);
        //设置同步回调和异步回调
        request.setReturnUrl(param.getReturnUrl());
        request.setNotifyUrl(param.getNotifyUrl());
        //执行网页支付请求
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        //判断支付宝响应结果
        if(response.isSuccess()) {
            //返回支付宝响应的支付表单html内容
            return response.getBody();
        }
        throw new Exception("发起支付失败");
    }

    /**
     * 从支付宝查询订单支付状态
     */
    public PayInfoDto getPayState(String orderNum) throws AlipayApiException {
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderNum+"\"}");
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        //输出
        String orderInfo= JSONUtil.parseObj(result).get("alipay_trade_query_response").toString();
        String payCode=JSONUtil.parseObj(orderInfo).get("code").toString();
        //支付宝响应10000表示说明用户已支付
        if("10000".equals(payCode)) {
            String payDate =JSONUtil.parseObj(orderInfo).get("send_pay_date").toString();
            String payState = JSONUtil.parseObj(orderInfo).get("trade_status").toString();
            PayInfoDto dto = new PayInfoDto(payDate, payState);
            return dto;
        }else {
            PayInfoDto dto = new PayInfoDto(null, "TRADE_FAIL");
            return dto;
        }
    }

    /**
     * 退款堂食订单
     */
    public boolean refund(SeatEatOrder orderInfo) throws AlipayApiException {
        System.out.println(orderInfo.getOrderNum());
        //创建退款组装参数对象
        AlipayTradeRefundRequest refundRequest = new AlipayTradeRefundRequest();
        double money = orderInfo.getTotalPrice().doubleValue();
        refundRequest.setBizContent("{\"out_trade_no\":\""+ orderInfo.getOrderNum() +"\","
                + "\"refund_amount\":\""+ money +"\","
                + "\"refund_reason\":\""+ "用户发起退款" +"\","
                + "\"out_request_no\":\""+ UUID.randomUUID().toString() +"\"}");
        //发送退款请求
        String result = alipayClient.execute(refundRequest).getBody();
        System.out.println(result);
        String code = JSONUtil.parseObj(JSONUtil.parseObj(result).get("alipay_trade_refund_response").toString()).get("code").toString();
        String fundChange = JSONUtil.parseObj(JSONUtil.parseObj(result).get("alipay_trade_refund_response").toString()).get("fund_change").toString();
        if(code.equals("10000") && fundChange.equals("Y")){
            //退款成功且有资金变化
            return true;
        }else{
            //退款失败
            return false;
        }

    }

    /**
     * 退款外送订单
     */
    public boolean refund(SendOrder orderInfo) throws AlipayApiException {
        System.out.println(orderInfo.getOrderNum());
        //创建退款组装参数对象
        AlipayTradeRefundRequest refundRequest = new AlipayTradeRefundRequest();
        double money = orderInfo.getOrderPrice().doubleValue();
        refundRequest.setBizContent("{\"out_trade_no\":\""+ orderInfo.getOrderNum() +"\","
                + "\"refund_amount\":\""+ money +"\","
                + "\"refund_reason\":\""+ "用户发起退款" +"\","
                + "\"out_request_no\":\""+ UUID.randomUUID().toString() +"\"}");
        //发送退款请求
        String result = alipayClient.execute(refundRequest).getBody();
        System.out.println(result);
        String code = JSONUtil.parseObj(JSONUtil.parseObj(result).get("alipay_trade_refund_response").toString()).get("code").toString();
        String fundChange = JSONUtil.parseObj(JSONUtil.parseObj(result).get("alipay_trade_refund_response").toString()).get("fund_change").toString();
        if(code.equals("10000") && fundChange.equals("Y")){
            //退款成功且有资金变化
            return true;
        }else{
            //退款失败
            return false;
        }

    }




}
